<template>
  <div class="content-section">
    <el-card shadow="hover" style="height: 730px">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
        </div>
      </template>

      <div class="form-area">
        <el-form label-width="250px" size="large" style="max-width: 800px">
          <!-- 头像 -->
          <el-form-item label="头 &nbsp;&nbsp; 像:">
            <div class="avatar-upload">
              <el-avatar :size="100" :src="avatarUrl"></el-avatar>
              <UserAvatar :originImgUrl="avatarUrl" @upload="uploadAvatar" ref="userAvatarRef"/>
            </div>
          
          </el-form-item>
          <!-- 昵称 -->
          <el-form-item label="用 户&nbsp;  名:">
            <div v-if="!isNicknameEditing" class="nickname-display">
              <el-text>{{ userInfo.userName }}</el-text>
              <el-icon class="edit-icon" @click="startEditNickname">
                <EditPen />
              </el-icon>
            </div>
            <el-input
              v-else
              ref="nicknameInput"
              v-model="tempNickname"
              @keyup.enter="saveNickname"
              @blur="saveNickname"
              @keyup.esc="cancelEditNickname"
              autofocus
            />

          </el-form-item>

          <!-- 密码 -->
          <el-form-item label="登录密码:">
            <div v-if="!isPasswordEditing" class="nickname-display">
              <el-text>{{ pwd }}</el-text>
              <el-icon class="edit-icon" @click="passwordDialog">
                <EditPen />
              </el-icon>
            </div>

          </el-form-item>



          <!-- 手机号 -->
          <el-form-item label="手机号码:">
            <el-text>{{ userInfo.phone }}</el-text>

            <el-icon class="edit-icon" @click="editPhone">
                <EditPen />
              </el-icon>
          </el-form-item>

          <!-- 邮箱 -->
          <el-form-item label="邮箱地址:">
            <div v-if="!isEmailEditing" class="email-display">
              <el-text>{{ userInfo.email }}</el-text>
              <el-icon class="edit-icon" @click="startEditEmail">
                <EditPen />
              </el-icon>
            </div>
            <el-input
              v-else
              ref="emailInput"
              v-model="tempEmail"
              @keyup.enter="saveEmail"
              @blur="saveEmail"
              size="small"
              placeholder="请输入新的邮箱"
              autofocus
            />
          </el-form-item>



            <!-- 个人简介 -->
            <el-form-item label="个人简介:">
            <div v-if="!isScriptEditing" class="intro-display">
              <el-input
                type="textarea"
                :rows="6"
                :model-value="userInfo.script"
                disabled
                style="width: 500px"
              />
              <el-icon class="edit-icon" @click="startEditScript">
                <EditPen />
              </el-icon>
            </div>
            <el-input
              v-else
              ref="scriptInput"
              v-model="tempScript"
              :rows="6"
              type="textarea"
              @keyup.enter.native="saveScript"
              @blur="saveScript"
              autofocus
            />
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 更换手机号弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="更改手机号" width="450px">
      <el-form :model="form" label-width="80px">
        <el-form-item label="新手机号" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入新手机号"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="验证码">
          <div class="code-input">
            <el-input
              v-model="form.code"
              placeholder="验证码"
              maxlength="4"
            />
            <el-button
              class="code-btn"
              :disabled="countdown > 0 || gettingCode"
              @click="getCode"
            >
              {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="changePhone">立即绑定</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 修改密码弹窗 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="500px">
    <el-form
      ref="passwordFormRef"
      :model="passwordForm"
      :rules="passwordRules"
      label-width="100px"
    >
      <el-form-item label="旧密码" prop="oldPwd"  v-if="showOldPassword">
        <el-input
          v-model="passwordForm.oldPwd"
          type="password"
          show-password
          placeholder="请输入当前密码"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="pwd">
        <el-input
          v-model="passwordForm.pwd"
          type="password"
          show-password
          placeholder="8-20位字母数字组合"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="pwd2">
        <el-input
          v-model="passwordForm.pwd2"
          type="password"
          show-password
          placeholder="请再次输入新密码"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="passwordLoading"
          @click="submitPasswordChange"
        >
          确认修改
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, watch, onUnmounted, onMounted ,computed} from 'vue'
import { ElMessage } from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'
import { useAuthStore } from '../../stores/index.js'
import { User } from '../../api/User.js'
import UserAvatar from "./userAvatar.vue";
const showOldPassword = computed(() => userInfo.value.pwd != 0)
// 引入 Pinia 中的用户数据
const authStore = useAuthStore()
const userInfo = ref({})
watch(
  () => authStore.userInfo,
  v => (userInfo.value = { ...v }),
  { immediate: true }
)
const emit = defineEmits(['update-user'])
// ---------- 头像上传 ------------
const userAvatarRef = ref(null)
const avatarUrl = ref(userInfo.value.headerPic || '')
const uploadAvatar = (file) => {
  let config = {
    headers: { 'Content-Type': 'multipart/form-data' }
  }
  const formData = new FormData()
  formData.append('headerPic', file.data,file.filename)
  User.uploadAvatar(formData,config)
    .then(res => {
      if (res.code === 0) {
        avatarUrl.value = res.data.headerPic.url
        emit('update-user', userInfo.value)
        authStore.updateUser({ headerPic: avatarUrl.value })
        userInfo.value.headerPic = avatarUrl.value
        ElMessage.success('头像上传成功')
        userAvatarRef.value.closeDialog()
      } else {
        throw new Error(res.message)
      }
    })
    .catch(err => {
      ElMessage.error(err.message || '上传失败')
    })
}

// ---------- 昵称编辑 ------------
const isNicknameEditing = ref(false)
const tempNickname = ref('')
const nicknameInput = ref(null)
const startEditNickname = () => {
  tempNickname.value = userInfo.value.userName || ''
  isNicknameEditing.value = true
  nextTick(() => nicknameInput.value?.focus())
}
const saveNickname = async () => {
  const name = tempNickname.value.trim()
  if (!name) {
    ElMessage.warning('昵称不能为空')
    return
  }
  try {
    const res = await User.updateNickname({ userName: name })
    if (res.code === 0) {
      authStore.updateUser({ userName: name })
      userInfo.value.userName = res.data.userName.content
      ElMessage.success('昵称修改成功')
      emit('update-user', userInfo.value)
    } else {
      throw new Error(res.message)
    }
  } catch (err) {
    ElMessage.error(err.message || '修改失败')
  } finally {
    isNicknameEditing.value = false
  }
}
const cancelEditNickname = () => {
  isNicknameEditing.value = false
}

// ---------- 个人简介编辑 ------------
const isScriptEditing = ref(false)
const tempScript = ref('')
const scriptInput = ref(null)
const startEditScript = () => {
  tempScript.value = userInfo.value.userScript || ''
  isScriptEditing.value = true
  nextTick(() => scriptInput.value?.focus())
}
const saveScript = async () => {
  const script = tempScript.value.trim()
  if (!script) {
    ElMessage.warning('个人简介不能为空')
    isScriptEditing.value = false
    return
  }
  try {
    const res = await User.updateUserScript({ userScript: script })
    if (res.code === 0) {
      authStore.updateUser({  script })
      ElMessage.success('个人简介更新成功')
    } else {
      throw new Error(res.message)
    }
  } catch (err) {
    ElMessage.error(err.message || '更新失败')
  } finally {
    isScriptEditing.value = false
  }
}

// ---------- 邮箱编辑 ------------
const isEmailEditing = ref(false)
const tempEmail = ref('')
const emailInput = ref(null)
const startEditEmail = () => {
  tempEmail.value = userInfo.value.email || ''
  isEmailEditing.value = true
  nextTick(() => emailInput.value?.focus())
}
const saveEmail = async () => {
  const email = tempEmail.value.trim()
  if (!email) {
    ElMessage.warning('邮箱不能为空')
    return
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    ElMessage.warning('邮箱格式不正确')
    return
  }
  try {
    const res = await User.updateEmail({ email })
    if (res.code === 0) {
      authStore.updateUser({ email })
      ElMessage.success('邮箱修改成功')
    } else {
      throw new Error(res.message)
    }
  } catch (err) {
    ElMessage.error(err.message || '修改失败')
  } finally {
    isEmailEditing.value = false
  }
}

// ---------- 更换手机号弹窗 ------------
const dialogFormVisible = ref(false)
const form = reactive({ phone: '', code: '', position: 'bind' })
const countdown = ref(0)
const gettingCode = ref(false)
const timer = ref(null)
const editPhone = () => {
  dialogFormVisible.value = true
}
const startCountdown = () => {
  if (timer.value) clearInterval(timer.value)
  timer.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer.value)
      timer.value = null
    }
  }, 1000)
}

const getCode = async () => {
  if (!/^\d{11}$/.test(form.phone)) {
    ElMessage.error('请输入正确手机号')
    return
  }
  gettingCode.value = true
  try {
    const res = await User.getPhoneCode({ phone: form.phone, position: form.position })
    countdown.value = res.data.getMsg.timer
    ElMessage.success('验证码已发送')
    startCountdown()
  } catch (err) {
    ElMessage.error(err.message || '发送失败')
  } finally {
    gettingCode.value = false
  }
}

const changePhone = async () => {
  if (!/^\d{11}$/.test(form.phone)) {
    ElMessage.error('请输入正确手机号')
    return
  }
  if (!/^\d{4}$/.test(form.code)) {
    ElMessage.error('请输入4位验证码')
    return
  }
  try {
    const res = await User.updatePhone({ phone: form.phone, code: form.code })
    if (res.code === 0) {
      authStore.updateUser({ phone: form.phone })
      ElMessage.success('手机号更换成功')
      dialogFormVisible.value = false
    } else {
      throw new Error(res.message)
    }
  } catch (err) {
    ElMessage.error(err.message || '绑定失败')
  }
}





// ---------- 修改密码弹窗 ------------
// 密码修改相关状态
const passwordDialogVisible = ref(false)
const passwordLoading = ref(false)
const passwordFormRef = ref(null)
const pwd=ref('*******')
const passwordForm = reactive({
  oldPwd: '',
  pwd: '',
  pwd2: ''
})
const passwordDialog=()=>{
  passwordDialogVisible.value=true
}
// 密码校验规则
// const validatePassword = (rule, value, callback) => {
//   if (!/(?=.*[a-zA-Z])(?=.*\d).{8,20}/.test(value)) {
//     callback(new Error('需包含字母和数字，8-20位'))
//   } else {
//     callback()
//   }
// }

// const validateConfirm = (rule, value, callback) => {
//   if (value !== passwordForm.pwd) {
//     callback(new Error('两次输入密码不一致'))
//   } else {
//     callback()
//   }
// }

// const passwordRules = {
//   oldPwd: [
//     { required: true, message: '请输入旧密码', trigger: 'blur' }
//   ],
//   pwd: [
//     { required: true, message: '请输入新密码', trigger: 'blur' },
//     { validator: validatePassword, trigger: 'blur' }
//   ],
//   pwd2: [
//     { required: true, message: '请确认新密码', trigger: 'blur' },
//     { validator: validateConfirm, trigger: 'blur' }
//   ]
// }

// 提交密码修改
const submitPasswordChange = async () => {
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true

    const res = await User.changePassword({
      oldPwd: passwordForm.oldPwd,
      pwd: passwordForm.pwd,
      pwd2: passwordForm.pwd2

    })

    if (res.code === 0) {
      ElMessage.success('密码修改成功')
      passwordDialogVisible.value = false
      // authStore.updateUser({ pwd: 1 })
      passwordFormRef.value.resetFields()
    } else {
      ElMessage.error(res.message || '密码修改失败')
    }
  } catch (err) {
    console.error('密码修改失败:', err)
  } finally {
    passwordLoading.value = false
  }
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer.value) clearInterval(timer.value)

})
onMounted(()=>{
  console.log(userInfo.value.pwd)
})
</script>

<style lang="scss" scoped>
.content-section {
  animation: fadeIn 0.3s ease;

  .form-area {
    width: 90%;
    margin: 0 auto;
    padding-top: 20px;
  }
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 20px;

  :deep(.el-upload) {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
}

.el-upload__tip {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

.nickname-display,
.intro-display,
.email-display {
  display: flex;
  align-items: center;
  gap: 8px;
}

.edit-icon {
  cursor: pointer;
  color: #409eff;
  font-size: 18px;
  transition: color 0.2s;
}
.edit-icon:hover {
  color: #66b1ff;
}

.code-input {
  display: flex;
  align-items: center;
}
.code-btn {
  margin-left: 10px;
  border: none;
  background: transparent;
  color: #0080d1;
}

.dialog-footer {
  text-align: right;
  padding: 10px 20px;
}

</style>
